import Config from '../config/index';
import qs from 'qs'
import md5 from 'js-md5'
import { Toast } from 'native-base'; 
import AsyncStorage from './AsyncStorage';
import { Platform } from "react-native";

//排序的函数
function objKeySort(obj) {
    var newkey = Object.keys(obj).sort();
　　//先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
    var newObj = {};//创建一个新的对象，用于存放排好序的键值对
    for (var i = 0; i < newkey.length; i++) {//遍历newkey数组
        newObj[newkey[i]] = obj[newkey[i]];//向新创建的对象中按照排好的顺序依次增加键值对
    }
    return newObj;//返回排好序的新对象
}


export default async (type = 'GET', uri, data) => {
	// Token
	let Token = await AsyncStorage.getItem("globalInfo");
	if (Token) {
		Token = JSON.parse(Token);
		Token = Token.token;
	}
	// 大写
	type = type.toUpperCase();
	// 地址判断
	uri.search("http") != '-1' ? uri = uri : uri = Config.API_PATH + uri;
	let startTime = new Date().getTime();
	
	try {
		let response = {};
		if (type === 'GET') {
			data = uri + '?' + qs.stringify(data)
			response = await fetch(data)
		} else {
			// 实体
			response = await fetch(
				uri, 
				{
					method: 'POST',
					headers: {
						Accept: 'application/json',
						'token': Token,
						'Content-Type': 'application/json'
					},
					body: JSON.stringify(data),
				}
			);
		}
		let responseJson = await response.json();

		let endTime = new Date().getTime();

		Config.Env === 'dev' && console.log(type,Token,uri,data);
		Config.Env === 'dev' && console.log(responseJson);
		Config.Env === 'dev' && console.log('开始时间',startTime,'结束时间：', endTime,'用时：', endTime-startTime);
		Config.Env === 'dev' && console.log();
		if(responseJson){
			if (responseJson.code != 200) {
				Toast.show({ text: responseJson.message,  position: "top", textStyle: { textAlign: "center" }, type: "warning" });
			}
		}else{
			responseJson = {};
		}

		return responseJson;
	} catch (error) {
		console.error(error);
	}
} 

